<template>
  <div id="app">
    <!-- 基础搜索 -->
    <el-header class="header">
      <el-menu :default-active="activeView" class="top-nav-menu" mode="horizontal">
        <el-menu-item index="2" @click="shouye">首页</el-menu-item>
        <el-menu-item index="xianhua" @click="xianhua">鲜花大厅</el-menu-item>
        <el-menu-item index="4" @click="showCart">订单查询</el-menu-item>
      </el-menu>
    </el-header>
    <div class="container no-padding">
      <table class="table mt10">
        <thead>
        <tr>
          <th>
            <div class="checkbox">
              <label>
                <input class="all" type="checkbox" v-model="allSelected" @change="selectAll($event)"> 全选
              </label>
            </div>
          </th>
          <th>商品图片</th>
          <th>花语</th>
          <th>单价</th>
          <th>库存</th>
          <th>数量</th>
          <th>小计</th>
          <th>操作</th>
        </tr>
        </thead>

        <tbody>
        <tr v-for="item in cartList" :key="item.id">
          <td>
            <div class="checkbox">
              <label>
                <input type="checkbox" v-model="item.selected" @change="updateSelection(item, $event)">
              </label>
            </div>
          </td>
          <td>
            <img :src="item.flower.fsrc" class="product-image" alt="商品图片">
          </td>
          <td>{{ item.flower.flangure }}</td>
          <td>{{ item.flower.price }}</td>
          <td>{{ item.flower.number }}</td>
          <td>
            <div class="input-group">
              <button @click="decreaseQuantity(item)">-</button>
              <input type="text" class="buy-count" v-model="item.num" readonly>
              <button @click="increaseQuantity(item)">+</button>
            </div>
          </td>
          <td>{{ (item.flower.price * item.num).toFixed(2) }} 元</td>
          <td>
            <button class="btn btn-danger" @click="removeFromCart(item)">删除</button>
          </td>
        </tr>
        </tbody>

        <tfoot>
        <tr id="last-tr">
          <td colspan="8" class="no-padding">
            <a href="http://localhost:8080/xianHua">继续购物</a> |
            已选择 <span class="choic-num">{{ selectedCount }}</span> 件 |
            <a href="#" @click="removeSelected">删除所选项</a>
            <a href="#" class="btn btn-primary buy fr ml10" @click="addOrder">下单</a>
            <span class="fr">合计 : <i class="total">{{ amount }}</i> 元</span>
          </td>
        </tr>
        </tfoot>
      </table>
    </div>

    <!-- 下单 -->
    <div v-if="orderModalVisible" class="modal">
      <div class="modal-content">
        <div><span class="close" @click="orderModalVisible = false">&times;</span>
          <h2>{{ username }}: 的下单信息</h2>
          <div v-for="(order, index) in currentOrder" :key="index">
            <div v-for="item in order.items" :key="item.id">
              <p><img :src="item.flower.fsrc" class="product-image" alt="商品图片" style="width: 100px; height: 100px;">
              </p>
              <p>商品id：{{ item.flower.fid }}</p>
              <p>商品名称：{{ item.flower.flangure }}</p>
              <p>数量：{{ item.num }}</p>
            </div>
            <div>
              <label for="address">收货地址：</label>
              <input type="text" v-model="order.address">
            </div>
          </div>
          <button @click="submitOrders">提交订单</button>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
import {v4 as UUID} from 'uuid';

export default {
  data() {
    return {
      money: 0,
      id: 0,
      username: '',
      dialogVisible: false,
      cartList: [
        {
          id: 20,
          flower: {
            fsrc: 'image-source-url',
            flangure: '花语描述',
            price: 100.00, // 确保商品单价不为 0
            number: 10, // 确保商品库存不为 0
          },
          num: 1, // 确保商品在购物车中的数量不为 0
          selected: false, // 商品是否被选中
        },
        // 其他商品项...
      ],
      userForm: {
        id: 0,
        username: '',
        password: '',
        iphone: '',
        src: '',
      },
      activeView: 'home', // 初始值根据你的应用逻辑来设置
      activeIndex: '1', // 默认激活的菜单项
      cartCount: 0, // 购物车数量
      src: '', // 存储头像地址
      user: { // 存储用户信息
        id: 0,
        username: '',
      },
      cartItems: [], // 购物车中的商品
      dialogVisibl: false, // 控制对话框显示
      showPersonalInfo: false, // 控制个人信息的显示
      title: '个人中心', // 模态框标题
      users: [], // 存储用户数据的数组
      formLabelWidth: '120px', // 表单项的标签宽度
      originalPassword: '', // 保存用于比较的原始密码
      showRecommendations: true, // 控制推荐内容的显示
      showPersonalCenter: false, // 初始值根据你的应用逻辑来设置
      dialogVisibles: false,// 控制模态框显示
      typesss: [], // 存储鲜花类型的数组
      types: {
        tid: 0,
        tname: '',
      },
      flowerList: [],
      flower: {
        fid: 0,
        fname: '',
        types: {
          tid: 0,
          tname: '',
        },
        faddress: '',
        flangure: '',
        src: '',
        users: [], // 存储用户数据的数组
        userForm: {
          id: 0,
          username: '',
          password: '',
          iphone: '',
          src: '',
        },
        shops: {
          sid: 0,
          sname: '',
          spassword: '',
          siphone: '',
          src: '',
        },
        typesss: [],
        price: '',
        number: 0, // 库存数量
      },
      shops: [], // 确保这里根据你的实际需求初始化 shops
      num: 1,
      errorImages: [
        'http://image.wncinema.com/img/2024-09-13/5EEAE2967DF94759A1BD43CD14694BED_hua5.webp&#39',
        'http://image.wncinema.com/img/2024-09-13/3335D50566524C1F8B5E7CA84DD111B2_hua2.webp&#39',
        'http://image.wncinema.com/img/2024-09-13/B4A8ADE595AC470993CA66AB2131F332_111.jpg&#39',
        'http://image.wncinema.com/img/2024-09-13/B122BAE2BBE44174A3F3A09060C706E9_hua3.webp&#39',
        'http://image.wncinema.com/img/2024-09-13/60F8CA35A84640EBB4B74FD2DD5D4CA3_hua1.webp&#39',
        'http://image.wncinema.com/img/2024-09-13/708B2DB739C84A62971E969215669305_hua6.webp&#39',
        'http://image.wncinema.com/img/2024-09-13/D9E2D59287D544B0A22A87C8C997B750_hua4..webp&#39',
        'http://image.wncinema.com/img/2024-09-13/6B6FD0DE816E4E57AFFA59ABFCF3AC2B_9.jpg&#39',
        'http://image.wncinema.com/img/2024-09-13/A25D41C340A449529BE443C00DF917A8_11.jpg&#39',
        'http://image.wncinema.com/img/2024-09-13/95E2A4DB4DDA40A3A2BA66D885083F81_3.jpg&#39',
      ],
      uid: 0,
      fid: 0,
      amount: 0,
      allSelected: false, // 新增变量，用于跟踪是否所有商品都被选中
      selectedCount: 0, // 用于显示已选择的商品数量
      selectedIds: [], // 用于存储已选择的商品ID
      order: {
        id: '',
        user: {
          id: '',
          username: '',
          password: '',
          iphone: '',
          src: ''
        },
        shops: {
          sid: '',
          sname: '',
          spassword: '',
          siphone: '',
          src: ''
        },
        flower: {
          fid: '',
          fname: '',
          faddress: '',
          flangure: '',
          fsrc: '',
          price: '',
          number: '',
          types: {
            tid: '',
            tname: '',
            sid: ''
          },
          shops: {
            sid: '',
            sname: '',
            spassword: '',
            siphone: '',
            src: ''
          }
        },
        oprice: '',
        createTime: '',
        state: 1,
        address: '',
        quantity: '',
      },
      orderModalVisible: false, // 控制订单模态框的显示
      orders: [], // 存储选中的订单商品
      currentOrder: [], // 当前正在处理的订单
      address: '', // 存储用户输入的地址
    };
  },

  methods: {
    // ----------------查询购物车数据----------------------------
    queryCart() {
      if (this.username === null || this.username === '') {
        this.$message.error('请先登录');
        return;
      } else {
        this.$axios({
          method: 'get',
          url: 'http://localhost:9091/creat/selectCreat',
          params: {
            uid: this.uid,
          },
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.cartList = res.data.data; // 更新购物车列表
            console.log('购物车数据:', this.cartList);
          } else {
            this.$message.error(res.data.message);
          }
        }).catch(error => {
          console.error('获取购物车数据失败:', error);
          this.$message.error('获取购物车数据失败');
        });
      }
    },

    // 拿到订单所有数据
    getOrder() {
      // 假设 this.orders 已经从后端获取到了数据
      this.cartList.forEach((creat) => {
        const order = {
          user: {
            id: creat.user.id,
            username: creat.user.username,
            password: creat.user.password,
            iphone: creat.user.iphone,
            src: creat.user.src,
          },
          shops: {
            sid: creat.flower.shops.sid,
            sname: creat.flower.shops.sname,
            spassword: creat.flower.shops.spassword,
            siphone: creat.flower.shops.siphone,
            src: creat.flower.shops.src,
          },
          flower: {
            fid: creat.flower.fid,
            fname: creat.flower.fname,
            faddress: creat.flower.faddress,
            flangure: creat.flower.flangure,
            fsrc: creat.flower.fsrc,
            price: creat.flower.price,
            number: creat.flower.number,
          },
          state: 1, // 状态
          address: '', // 初始地址为空
          quantity: creat.num, // 数量
          oprice: creat.flower.price * creat.num, // 订单总价
        };
        this.currentOrder.push(order);
      });

      //   // 显示订单数据
      //   this.currentOrder.forEach((order, index) => {
      //     alert(`订单 ${index + 1}:
      // 用户id: ${order.user.id}
      // 商家id: ${order.shops.sid}
      // 商品id: ${order.flower.fid}
      // 状态: ${order.state}
      // 数量: ${order.quantity}
      // 订单总价: ${order.oprice}`);
      //   });
    },

// ------------------下单------------------------
    addOrder() {
      this.getOrder(); // 确保 getOrder 被调用
      this.getSelectedIds(); // 更新并打印已选择的商品ID
      this.orderItems = this.cartList.filter((item) => item.selected); // 获取选中的商品
      if (this.orderItems.length > 0) {
        this.currentOrder = []; // 清空当前订单
        // 遍历选中的商品项，为每个商品创建一个新的订单对象
        this.orderItems.forEach((item) => {
          const newUUID = UUID(); // 为每个订单生成新的 UUID
          const newOrder = {
            'oid': newUUID, // 订单ID
            user: {
              'id': item.user.id, // 用户ID
            },
            shops: {
              'sid': item.flower.shops.sid, // 商家ID
            },
            flower: {
              'fid': item.flower.fid, // 商品ID
            },
            'items': [item], // 订单中的商品项
            'address': '', // 初始地址为空
            'quantity': item.num, // 设置数量
            'oprice': (item.flower.price * item.num).toFixed(2), // 计算小计
            'state': 1, // 初始状态设置为 'pending'
            'createTime': new Date().toISOString().slice(0, 19).replace('T', ' '), // 创建时间
          };
          this.currentOrder.push(newOrder) // 将每个商品作为一个单独的订单添加到当前订单中
        });
        this.orderModalVisible = true; // 显示模态框
      } else {
        alert('请先选择商品');
      }
    },

// ------------------提交订单------------------------
    submitOrders() {
      // 地址不能为空
      if (this.address == '' && this.address == null) {
        alert('请填写地址');
        return;
      }
      if (this.currentOrder.length === 0) {
        alert('没有可提交的订单');
        return;
      }
      // 确保 currentOrder 是一个数组，即使只有一个订单
      const ordersToSubmit = this.currentOrder;
      this.$axios({
        url: 'http://localhost:9091/Order/addOrder',
        method: 'post',
        data: ordersToSubmit
      }).then(response => {
        if (response.data.code === 200) {
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          //   刷新页面
          this.queryCart()
          //   关闭模态框
          this.orderModalVisible = false;
          //   获取下单的id
          this.getSelectedIds();
          this.remove()
        }
      });
    },

    // 删除-------------------------
    remove() {
      let ids = this.selectedIds;
      this.$axios({
        url: 'http://localhost:9091/creat/delete/' + ids,
        method: 'POST'
      }).then(response => {
        if (response.data.code === 200) {
          this.$message();
          this.$message({
            type: 'success',
            message: response.data.msg
          });
          //   刷新页面
          this.queryCart()
          //删除数据，选中的小计从合计中减去
          this.amount = 0
        }
      });
    },


    // 删除-------------------------
    removeFromCart(cart) {
      this.selectedIds = [];
      this.selectedIds.push(cart.id);
      console.log(cart.id);
      this.removeSelected();
      this.selectedIds = [];
    },
    removeSelected() {
      let ids = this.selectedIds;
      this.$confirm('此操作将永久删除该' + ids + '文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('-----' + ids);
        if (ids.length != 1) { // 多选的时候，什么都没有选择
          // 先从复选框中提取数据复制给ids
          if (this.multipleSelection != undefined) {
            this.multipleSelection.forEach((value) => ids.push(value.id));
          }
          // 如果赋值之后，ids还是空，说明没有选
          if (ids.length === 0) {
            this.$message({
              type: 'warning',
              message: '请先选择要删除的数据'
            });
            return;
          }
        }
        this.$axios({
          url: 'http://localhost:9091/creat/delete/' + ids,
          method: 'POST'
        }).then(response => {
          if (response.data.code === 200) {
            this.$message();
            this.$message({
              type: 'success',
              message: response.data.msg
            });
            //   刷新页面
            this.queryCart()
            //删除数据，选中的小计从合计中减去
            this.amount = 0
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    getSelectedIds() {
      this.selectedIds = this.cartList.filter(item => item.selected).map(item => item.id);
      console.log('Selected IDs:', this.selectedIds); // 打印已选择的商品ID
    },

    // 金额算法-----------------------------------------
    calculateTotalAmount() {
      this.amount = this.cartList.reduce((total, cart) => {
        if (cart.selected) {
          total += cart.flower.price * cart.num;
        }
        return total;
      }, 0).toFixed(0);
    },

    selectAll(event) {
      const checked = event.target.checked;
      this.allSelected = checked;
      this.cartList.forEach(cart => {
        cart.selected = checked;
      });
      this.calculateTotalAmount(); // 重新计算总金额
    },

    increaseQuantity(cart) {
      if (cart.flower.number > 0 && cart.num < 100) {
        cart.num++;
        cart.flower.number--;
        if (cart.selected) {
          this.amount = Number(this.amount) + Number(cart.flower.price);
        }
      }
    },

    decreaseQuantity(cart) {
      if (cart.num > 1) {
        cart.num--;
        cart.flower.number++;
        if (cart.selected) {
          this.amount = Number(this.amount) - Number(cart.flower.price);
        }
      }
    },

    updateSelection(item, event) {
      item.selected = event.target.checked;
      const allSelected = this.cartList.length > 0 && this.cartList.every(cart => cart.selected);
      this.allSelected = allSelected;
      this.getSelectedIds(); // 更新并打印已选择的商品ID
      console.log(`商品 ${item.id} 选中状态: ${item.selected}`);
      this.calculateTotalAmount(); // 重新计算总金额
    },

    // calculateTotalAmount() {
    //   this.amount = this.cartList.reduce((total, cart) => {
    //     total = cart.flower.price * cart.num;
    //     if (cart.selected) {
    //       this.amount += total;
    //     } else {
    //       this.amount -= total;
    //     }
    //   }, 0).toFixed(0);
    // },
    //
    // selectAll(event) {
    //   this.amount = 0;
    //   const checked = event.target.checked;
    //   this.allSelected = checked;
    //   this.cartList.forEach(cart => {
    //     cart.selected = checked;
    //   });
    //   this.calculateTotalAmount();
    // },
    //
    // increaseQuantity(cart) {
    //   if (cart.flower.number > 0 && cart.num < 100) {
    //     cart.num++;
    //     cart.flower.number--;
    //     if (cart.selected) {
    //       // 确保操作是在数字之间进行
    //       this.amount += Number(cart.flower.price);
    //     }
    //   }
    // },
    //
    // decreaseQuantity(cart) {
    //   if (cart.num > 1) {
    //     cart.num--;
    //     cart.flower.number++;
    //     if (cart.selected) {
    //       // 确保操作是在数字之间进行
    //       this.amount -= Number(cart.flower.price);
    //     }
    //   }
    // },
    //
    // updateSelection(item, event) {
    //   item.selected = event.target.checked;
    //   const allSelected = this.cartList.length > 0 && this.cartList.every(cart => cart.selected);
    //   this.allSelected = allSelected;
    //   this.getSelectedIds(); // 更新并打印已选择的商品ID
    //   console.log(`商品 ${item.id} 选中状态: ${item.selected}`);
    //   if (item.selected) {
    //     // 确保操作是在数字之间进行
    //     this.amount += Number(item.flower.price) * Number(item.num);
    //   } else {
    //     // 确保操作是在数字之间进行
    //     this.amount -= Number(item.flower.price) * Number(item.num);
    //   }
    // },


    // queryCart() {
    //   if (this.username === null || this.username === '') {
    //     this.$message.error('请先登录');
    //     return;
    //   } else {
    //     this.$axios({
    //       method: 'get',
    //       url: 'http://localhost:9091/creat/selectCreat',
    //       params: {
    //         uid: this.uid,
    //       },
    //       headers: {
    //         'Content-Type': 'application/json'
    //       }
    //     }).then(res => {
    //       if (res.data.code === 200) {
    //         this.cartList = res.data.data; // 更新购物车列表
    //       } else {
    //         this.$message.error(res.data.message);
    //       }
    //     }).catch(error => {
    //       console.error('获取购物车数据失败:', error);
    //       this.$message.error('获取购物车数据失败');
    //     });
    //   }
    // },

    initializeCartList() {
      // 假设从服务器获取购物车数据或设置默认值
      this.cartList = [];
    },

    selectName() {
      this.$axios({
        method: 'post',
        url: 'http://localhost:9091/user/selectOne',
        data: {
          username: this.username,
        },
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        if (res.data && res.data.data) {
          this.uid = res.data.data.id;
          this.userForm = res.data.data;
          this.queryCart();
        } else {
          console.error('头像数据获取失败');
        }
      });
    },

    getCookie(name) {
      let nameEQ = name + "=";
      let ca = document.cookie.split(';');
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
      }
      return '';
    },

    getToken() {
      return localStorage.getItem('userToken');
    },

    shouye() {
      this.$router.push('/')
    },
    xianhua() {
      this.$router.push('/xianHua')
    },
    showCart() {
      this.$router.push('/userOrder')
    },
  },
  created() {
    this.username = this.getCookie('username');
    this.selectName()
    this.initializeCartList();
  },
};
</script>

<style scoped>
.container {
  width: 100%;
  padding: 0;
  margin: 0 auto;
}

.table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.table thead {
  background-color: #f7f7f7;
}

.table th,
.table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.table .product-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}

.input-group {
  display: flex;
  align-items: center;
}

.input-group button {
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  color: #333;
  padding: 5px 10px;
  cursor: pointer;
}

.input-group button:hover {
  background-color: #e9e9e9;
}

.buy-count {
  border: 1px solid #ddd;
  padding: 5px;
  text-align: center;
  width: 50px;
  margin: 0 5px;
}

.btn-danger {
  color: #fff;
  background-color: #d9534f;
  border-color: #d43f3a;
  border-radius: 4px;
  padding: 5px 10px;
}

.btn-danger:hover {
  background-color: #c9302c;
  border-color: #ac2925;
}

.btn-primary {
  color: #fff;
  background-color: #337ab7;
  border-color: #2e6da4;
  border-radius: 4px;
  padding: 5px 10px;
}

.btn-primary:hover {
  background-color: #286090;
  border-color: #204d74;
}

.fr {
  float: right;
}

.mt10 {
  margin-top: 10px;
}

.no-padding {
  padding: 0;
}

.checkbox label {
  margin-bottom: 0;
  cursor: pointer;
}

.choic-num {
  margin-left: 5px;
}

.total {
  margin-left: 5px;
  color: #f00;
}

.remove {
  margin-left: 10px;
  text-decoration: none;
  color: #d9534f;
}

.remove:hover {
  text-decoration: underline;
}

.buy {
  margin-top: 10px;
}

/*下单*/
.modal {
  display: block;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

.close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

.modal-content[data-v-10a979e4] {
  background-color: #fefefe;
  margin: 10% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 45%;
}
</style>